<!DOCTYPE html>
<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org" style="overflow: hidden">
<head>
    <title> 新增商品 </title>
    <th:block th:include="~{common/common::commonHead}"/>
</head>
<style>
    .input-num, .btn-jia, .btn-jian{
        display: inline-block;
        width: 28px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        font-size: 18px;
        color: #999;
        cursor: pointer;
        border: 1px solid #e6e6e6;
    }
    .input-num{
        width: 58px;
        height: 26px;
        color: #333;
        border-left: 0;
        border-right: 0;
    }
    .input-num:hover{
        color: black;
    }
</style>
<body data-width="1000" data-height="720">
<div class="widget-body">
    <p class="widget-hint">
        <span id="balance">账户余额：<strong>  </strong>元</span>
        <span id="availableAmount">本月剩余消费额度：<strong>  </strong> 元</span>
        <span id="money">待结算金额：<strong>  </strong> 元</span>
        <span id="consumptionThreshold">消费阈值：<strong>  </strong></span>
        <!--<a class="widget-details" href="../model/accountDetail.html">-->
            <!--账户详情 >-->
        <!--</a>-->
    </p>
    <ul class="nav nav-tabs tabs-flat" id="myTab11"></ul>
    <div class="tab-content tabs-flat">
        <div id="ZOObaby" class="tab-pane in active">
            <div class="row add-modity">
                <div class="col-md-3 col-sm-3 col-xs-12">
                    <div class="widget">
                        <h2 class=" widget-shopping ">
                            购物车
                            <a class="history-list" onclick="confirm();">订单查看 </a>
                        </h2>
                        <div class="ct-cart">
                            <span class="ct-cart-empty">你的购物车为空</span>
                            <span class="ct-cart-total hide" onchange="settle();">￥0</span>
                            <ol class="hide"></ol>
                            <button class="ct-cart-clear hide">清空购物车</button>
                            <button type="submit" class="ct-cart-checkout hide"> 下单 </button>
                        </div>

                    </div>
                </div>
                <div class="col-md-9 col-sm-9 col-xs-12" style="height: 100%;">
                    <div class="row right-modity" id="goodsList"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<!--Page Related Scripts-->
</body>
</html>
<script>
    $(function(){
        // 用来记录购物车中的商品数据
        var goodsToBuy = [];
        var myTab = $("#myTab11");
        //加载商品 添加购物车
        function check(){
            myTab.find("li").off("click").removeClass("active");
            $(this).addClass("active");
            myTab.find("li a").on("click",function (e) {
                e.preventDefault();
                return false;
            });
            var id=$(this).attr("data-id");
            $.doAjax("innerGoods/listGoodsUp",{"goodsType":id},function(data){
                shopping(data, id);
                $("#goodsList").find("img").each(function () {
                    var width = $(this).parent().width();
                    $(this).height(width);
                });
                $("#goodsList").find(".btn-jia").on("click", function () {
                });
                myTab.find("li").on("click",check);
                myTab.find("li a").off("click");
            });
        }
        var cart = $(".ct-cart");
        //选项卡显示
        $.doAjax("goods/listGoodsTypeHasGoods",function (goodsTypeList) {
            createTypeName(goodsTypeList);
            myTab.find("li").on("click", check);
            myTab.find("li:first").trigger("click");
        }, function (error) {
            $.error(error.msg);
        });
        // 下单
        $(".ct-cart-checkout").on("click", addOrder);
        $(".ct-cart-clear").on("click", clearCart);
        // 下单
        function addOrder() {
            $(".ct-cart-checkout").off("click").text("正在下单");
            var arr = [];
            $(".ct-cart").find("ol li").each(function (dx, li) {
                var goodsId = $(li).attr("data-id");
                var count = $(li).find("input").val();
                arr.push({
                    goodsId: goodsId,
                    goodsCount: count
                });
            });
            var json = JSON.stringify(arr);
            $.doAjax("orderPrisoner/addOrderPrisoner",{idAndCounts:json}, function () {
                $.success("下单成功");
                $(".ct-cart-checkout").on("click",addOrder).text("下单");
                clearCart();
            }, function (error) {
                $.error(error.msg);
                $(".ct-cart-checkout").on("click",addOrder).text("下单");
            });
        }
        // 清空购物车
        function clearCart(goodsId) {
            $(".ct-cart").find("ol").empty();
            $("#goodsList").find("input").val(0);
            goodsToBuy = [];
            settle();
        }
        //计算总价
        function settle(){
            var totalPrice = 0;
            cart.find("ol li").each(function (dx, li) {
                var sellPrice =$(li).attr("data-price");
                var value = $(li).find("input").val();
                sellPrice = Number(sellPrice);
                value = Number(value);
                var price;
                if (value === undefined) {
                    value = 1;
                    price = sellPrice * value
                } else {
                    price = sellPrice * value
                }
                totalPrice += price;
            });
            totalPrice /= 100;
            cart.find(".ct-cart-total").text("￥" + totalPrice.toFixed(2));

            if (totalPrice === 0) {
                cart.find(".ct-cart-empty").removeClass("hide");
                cart.children().not(".ct-cart-empty").addClass("hide");
            }
        }
        // 创建选项卡
        function createTypeName(arr){
            var options = "";
            $.each(arr,function(i,value){
                options +="<li data-id='"+value.id+"'>"+"<a data-toggle='tab'>"+value.typeName+"</a>"+"</li>";
            });
            myTab.html(options);

        }
        // 加载商品
        function shopping(a){
            $("#goodsList").empty();
            $.each(a,function(i,value){
                var shoppingCart = $(SHOPPING_CART.join(""));
                $("#goodsList").append(shoppingCart);
                shoppingCart.find("img").attr("src",value.goodsImg);
                shoppingCart.find(".ct-product-title").text(value.goodsName);
                shoppingCart.find(".product-price").text("￥"+(value.goodsSellPrice/100));
                shoppingCart.find(".product-price").attr("data-code",value.goodsSellPrice);
                shoppingCart.find(".ct-product-unit").text(value.goodsUnit);
                shoppingCart.find(".ct-product-spec").text(value.goodsSpec);
                shoppingCart.find(".ct-product").attr("data-id", value.id);
                shoppingCart.find(".btn-jian").on("click",function(){
                    minus(value.id);
                });
                shoppingCart.find(".btn-jia").on("click",function(){
                    var product = $(this).closest(".ct-product");
                    var goodsId = product.attr("data-id");
                    var goods = goodsToBuy[goodsId];
                    if (goods === null || goods === undefined) {
                        product.find("input").val(1);
                        var sellPrice =product.find(".product-price").attr("data-code");
                        var goodsName = product.find(".ct-product-title").text();
                        var goodsSellPrice = product.find(".product-price").text();
                        var goodsSpec = product.find(".ct-product-spec").text();
                        var goodsUnit = product.find(".ct-product-unit").text();
                        var cart = $(".ct-cart");
                        cart.find(".ct-cart-empty").addClass("hide");
                        cart.children().not(".ct-cart-empty").removeClass("hide");
                        var ol =cart.find("ol");
                        goods = {};
                        goods.id = goodsId;
                        goods.price = sellPrice;
                        goods.goodsSellPrice = goodsSellPrice;
                        goods.spec = goodsSpec;
                        goods.unit = goodsUnit;
                        goods.name = goodsName;
                        goods.count = 1;
                        goodsToBuy[goodsId] = goods;
                        ol.append(createOrderToBuyItem(goods));
                    } else {
                        plus(value.id);
                    }
                    settle();
                });

                var goods = goodsToBuy[value.id];
                if (goods !== null && goods !== undefined) {
                    shoppingCart.find("input").val(goods.count);
                }
            });

        }

        // 创建左侧购物车商品列表
        function createOrderToBuyItem(goods) {
            var li = [];
            li.push("<li class='animated fadeIn' data-id=''>");
            li.push("<span class='ct-cart-name'></span>");
            li.push("<div class='ct-cart-sum'>");
            li.push("<span class='ct-cart-price'></span>");
            li.push("<div class='ct-cart-amount'>");
            li.push("<button class='btn btn-d'> ");
            li.push("<span class='fa fa-minus'></span>");
            li.push("</button>");
            li.push("<input type='number' min='1' value='1' class='ct-cart-input' readonly>");
            li.push("<button class='btn btn-add' id='btn-add'>");
            li.push("<span class='fa fa-plus'></span>");
            li.push("</button>");
            li.push("</div>");
            li.push("</div>");
            li.push("<button class='ct-cart-remove'>×</button>");
            li.push("</li>");
            li = $(li.join(""));
            li.attr("data-id", goods.id);
            li.find(".ct-cart-name").text(goods.name);
            li.find(".ct-cart-price").text(goods.goodsSellPrice);
            li.find(".ct-cart-unit").text(goods.unit);
            li.find(".ct-cart-spec").text(goods.spec);
            li.find(".ct-cart-remove").on("click",function(){
                li.remove();
                var $right = $("#goodsList").find("div.ct-product[data-id='"+goods.id+"']");
                $right.find("input").val(0);
                goodsToBuy[goods.id] = undefined;
                settle();
            });
            li.attr("data-price", goods.price);
            li.find(".btn-d").on("click",function(){
                minus(goods.id);
            });
            li.find(".btn-add").on("click",function(){
                plus(goods.id);
            });
            li.find("input").on("change", function () {
                settle();
            });

            return li;
        }
        // 购买数量加
        function plus(goodsId){
            var $left = $(".ct-cart").find("li[data-id='"+goodsId+"']");
            var $right = $("#goodsList").find("div.ct-product[data-id='"+goodsId+"']");
            var value = goodsToBuy[goodsId].count;
            value++;
            goodsToBuy[goodsId].count = value;
//            var value = $right.find("input").val();
//            value = parseInt(value) + 1;
            $left.find("input").val(value);
            $right.find("input").val(value);

            settle();
        }
        // 购买数量减
        function minus(goodsId){
            var $left = $(".ct-cart").find("li[data-id='"+goodsId+"']");
            var $right = $("#goodsList").find("div.ct-product[data-id='"+goodsId+"']");
            var value = goodsToBuy[goodsId].count;
            value--;
            goodsToBuy[goodsId].count = value;
            if (value < 0) {
                value = 0;
            }
            $left.find("input").val(value);
            $right.find("input").val(value);
            if (value === 0) {
                $left.remove();
                goodsToBuy[goodsId] = undefined;
            }
            settle();
        }
        //加载犯人账户信息
        var prisonerId =$.getUrlParam('prisonerId');
        $.doAjax("prisonerAccount/getPrisonerAccount",{id:prisonerId},function(data){
            $("#balance").children().html("￥"+(Number(data['balance']))/100);
            $("#availableAmount").children().html("￥"+(Number(data['availableAmount']))/100);
            $("#consumptionThreshold").children().html("￥"+(Number(data['consumptionThreshold']))/100);
        });
        //加载犯人待结算金额
        $.doAjax("prisonerSettlement/getSettlementMoney",{id:prisonerId},function(data){
            $("#money").children().html("￥"+(Number(data['money']))/100);
        });
    });


    const SHOPPING_CART=[];
    SHOPPING_CART.push("" +
        " <div class='col-sm-3 col-xs-4'>");
    SHOPPING_CART.push("  <div class='ct-product'>");
    SHOPPING_CART.push("     <div class='image'>");
    SHOPPING_CART.push("        <img src='' alt='商品图片'>");
    SHOPPING_CART.push("      </div>");
    SHOPPING_CART.push("      <div class='inner'>");
    SHOPPING_CART.push("        <h2 class='ct-product-title'></h2>");
    SHOPPING_CART.push("        <span class='product-price'></span>");
    SHOPPING_CART.push("        <div>");
    SHOPPING_CART.push("          <span class='ct-product-unit'></span>");
    SHOPPING_CART.push("          <span class='ct-product-spec'></span>");
    SHOPPING_CART.push("        </div>");
    SHOPPING_CART.push("        <button class='btn-jian' id='btn-jian'>-</button>");
    SHOPPING_CART.push("        <input type='text' min='1' value='0' class='input-num' readonly> ");
    SHOPPING_CART.push("        <button class='btn-jia' id='btn-jia'>+</button>");
    SHOPPING_CART.push("      </div>");
    SHOPPING_CART.push("  </div>");
    SHOPPING_CART.push("</div>");
    //查看订单
    (function($){
        $.getUrlParam
            = function(name)
        {
            var reg
                = new RegExp("(^|&)"+
                name +"=([^&]*)(&|$)");
            var r
                = window.location.search.substr(1).match(reg);
            if (r!=null) return unescape(r[2]); return null;
        }
    })(jQuery);
    function confirm(){
        var prisonerId =$.getUrlParam('prisonerId');
        window.location.href="order/confirmReceipt.html?prisonerId="+prisonerId+"";
    }
</script>
